<?php
namespace App\Http\Middleware\Base\Exists\Trade;

use Closure;
use App\Models\Trade\Demand\DemandModel;
use App\Exceptions\Response\Middleware\MiddlewareException;
use App\Exceptions\Response\Middleware\MiddlewareCode;

/**
 * 数据存在检查
 */
class Demand
{

    /**
     * 前置 | 后置
     *
     * @param \Illuminate\Http\Request $request            
     * @param \Closure $next            
     * @return \Closure $next
     */
    public function handle($request, Closure $next)
    {
        validator($request->all(), [
            'id' => 'nullable|integer|min:1'
        ])->validate();
        
        if (($id = $request->input('id')) && DemandModel::findById($id, ['id'])->isEmpty()) {
            throw new MiddlewareException(MiddlewareCode::MIDDLEWARE_DATA_NOT_EXIST);
        }
        
        return $next($request);
    }
}